package cn.usian.service.service.impl;

import cn.usian.common.R;
import cn.usian.dao.CategoryDao;
import cn.usian.entity.Category;
import cn.usian.exception.NameException;
import cn.usian.service.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryDao categoryDao;

    @Override
    public R findPage(int page, int pageSize) {
        //创建Page对象
        Page<Category> pageInfo=new Page<>(page,pageSize);
        //增加排序的条件
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        Page<Category> categoryPage = categoryDao.selectPage(pageInfo, queryWrapper);
        return R.success(categoryPage);
    }


    @Override
    public void save(Category category) {
        //判定分类名是否存在
        if(findByName(category.getName())!=null){
            throw new NameException(category.getName());
        }
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryDao.insert(category);
    }
    @Override
    public Category findByName(String name) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName,name);
        return categoryDao.selectOne(queryWrapper);
    }



    @Override
    public void update(Category category) {
        categoryDao.updateById(category);
    }

    @Override
    public List<Category> findAll() {
        return categoryDao.selectList(null);
    }

    @Override
    public R list(int type) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getType,type);
        return R.success(categoryDao.selectList(queryWrapper));
    }
}
